package service;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.UserDao;
import entry.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@MultipartConfig
@WebServlet("/upload")
public class UpLoadServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        // 得到文件
        Part part = req.getPart("myImage");
        // 得到当前对象
        resp.setContentType("text/json; charset=utf8");
        HttpSession session = req.getSession(false);
        UserDao userDao = new UserDao();
        User sessionUser = (User) session.getAttribute("user");// 取出会话里的 user对象

        // 得到用户的新用户名
        String photoName = sessionUser.getUsername();
        int photoNumber = Integer.parseInt(sessionUser.getPhoto().split("_")[1])+1;
        sessionUser.setPhoto(photoName + "_" + photoNumber);// 更新用户的照片信息

        // 删除原来的照片
        String path = "/root/tomcat/apache-tomcat-8.5.78/webapps/blog/image/";
        User.deletePhoto(sessionUser.getUsername(), path);
        // 传入新照片
        path += photoName + "_" + photoNumber + ".png";
        part.write(path);

        // 更新数据库信息
        userDao.updateUser(sessionUser.getUserId(), sessionUser);
        // 更新 session对象
        session.removeAttribute("user");
        session.setAttribute("user", sessionUser);

        resp.sendRedirect("main.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        User sessionUser = (User) session.getAttribute("user");// 会话里 user对象

        // 返回user对象
        resp.setContentType("application/json; charset=utf8");
        String retString = objectMapper.writeValueAsString(sessionUser);
        resp.getWriter().write(retString);
    }
}
